// 定义跟收藏相关的路由
const Router = require('koa-router');
const router = new Router();

const { addMyLike, isLike, deteleLike, getMyLike, addCommonLike, deteleCommonLike } = require('../controllers/index.js');

router.prefix('/likes')

router.post('/addMyLike', async (ctx, next) => {
  const params = ctx.request.body
  try {
    const res = await addMyLike(params)
    if (res.affectedRows === 1) {
      await addCommonLike(params.cookId)
      ctx.body = {
        code: 200,
        flag: true,
        message: '收藏成功',
      }
    } else {
      ctx.body = {
        code: 200,
        flag: false,
        message: '您已经收藏过',
      }
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器异常',
    }
  }




})

router.post('/isLike', async (ctx, next) => {
  const params = ctx.request.body

  try {
    const res = await isLike(params)
    if (res.length > 0) {
      ctx.body = {
        code: 200,
        flag: true,
        message: '已收藏',
      }
    } else {
      ctx.body = {
        code: 200,
        flag: false,
        message: '未收藏',
      }
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器异常',
    }
  }
})

router.post('/deteleLike', async (ctx, next) => {
  const params = ctx.request.body

  try {
    const res = await deteleLike(params)
    if (res.affectedRows > 0) {
      await deteleCommonLike(params.cookId)
      ctx.body = {
        code: 200,
        message: '取消成功',
      }
    } else {
      ctx.body = {
        code: 200,
        message: '取消失败',
      }
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      message: '服务器异常',
    }
  }
})

router.get('/getMyLike', async (ctx, next) => {
  const userId = ctx.query.userId
  try {
    const res = await getMyLike(userId);
    if (res.length) {
      ctx.body = {
        code: 200,
        data: res,
        message: '查询成功'
      }
    } else {
      ctx.body = {
        code: 200,
        data: [],
        message: '暂无数据'
      }
    }
  } catch (error) {
    ctx.body = {
      code: 500,
      data: error,
      message: '服务器异常'
    }
  }
})

module.exports = {
  likesRouter: router
};